<?php

 
 /*
  * Example: 
  * $authStorage    = new RedMVC\Auth\Storage\Db(
  *     array("SELECT * FROM session WHERE sessionId='%s'", array(RedMVC\Session::id())),
  *     array("SELECT * FROM session WHERE sessionId='%s'", array(RedMVC\Session::id())),
  *     array("INSERT INTO session (sessionId, dateTime, authData) VALUES('%s', NOW(), '%s') ON DUPLICATE KEY UPDATE dateTime=NOW()", array(RedMVC\Session::id())),
  *     array("DELETE FROM session WHERE sessionId='%s'", array(RedMVC\Session::id()))
  * );
  * RedMVC\Auth::setStorage($authStorage);
  */    

namespace RedMVC\Auth\Storage;
use RedMVC;

/**
 * Db class
 *  
 * @category    RedMVC
 * @package     Auth
 * @subpackage  Storage 
 * @author      Jan Fischer, bitWorking <info@bitworking.de>
 */
class Db implements IStorage{

    protected $_db;
    protected $_sqlHas;
    protected $_sqlRead;
    protected $_sqlWrite;
    protected $_sqlClear;
    protected $_authDataField = 'authData';

    public function __construct(array $sqlHas, array $sqlRead, array $sqlWrite, array $sqlClear){
        $this->_sqlHas      = $sqlHas;
        $this->_sqlRead     = $sqlRead;
        $this->_sqlWrite    = $sqlWrite;
        $this->_sqlClear    = $sqlClear;
    }
    
    public function setDb($db){
        $this->_db = $db;
    }
    
    protected function _getDb(){
        if(null === $this->_db){
            $this->_db = RedMVC\Registry::get('RedMVC_Db');
        }
        return $this->_db;
    }
    
    public function setAuthDataField($authDataField){
        $this->_authDataField = $authDataField;
    }

    public function hasAuthData(){
        $db     = $this->_getDb();
        $result = call_user_func_array(array($db, 'fetch'), $this->_sqlHas);
        return (count($result) > 0);
    }
    
    public function read(){
        $db     = $this->_getDb();
        $result = call_user_func_array(array($db, 'fetch'), $this->_sqlRead);
        if(count($result) > 0){
            return unserialize($result[0][$this->_authDataField]);
        }
    }
    
    public function write(array $authData){
        $db     = $this->_getDb();
        $this->_sqlWrite[1][] = serialize($authData);
        $result = call_user_func_array(array($db, 'query'), $this->_sqlWrite);
    }
    
    public function clear(){
        $db     = $this->_getDb();        
        $result = call_user_func_array(array($db, 'query'), $this->_sqlClear);
    }

}